package com.gftBrazil.BankSystem.view;

import com.gftBrazil.BankSystem.tableModel.ClienteTableModel;
import com.gftBrazil.BankSystem.bean.ClienteBean;
import com.gftBrazil.BankSystem.bean.ClienteFisicoBean;
import com.gftBrazil.BankSystem.bean.ClienteJuridicoBean;
import com.gftBrazil.BankSystem.bean.enums.EstadoCliente;
import com.gftBrazil.BankSystem.bean.enums.Permissao;
import com.gftBrazil.BankSystem.bean.enums.UnidadeFederativa;
import com.gftBrazil.BankSystem.business.ClienteBusiness;
import com.gftBrazil.BankSystem.controller.cliente.ClienteFisicoController;
import com.gftBrazil.BankSystem.exceptions.AcessoNegadoException;
import com.gftBrazil.BankSystem.util.Ambiente;
import com.gftBrazil.BankSystem.util.Sorteador;
import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

/**
 *
 * @author JRSS
 */
public class ConsultaClienteView extends javax.swing.JInternalFrame {

    private final Map<Integer, ClienteBean> clientesMap;
    private final List<ClienteBean> clientes;
    private List<ClienteBean> clientesTable;
    private ClienteBean cliente;

    /**
     * Creates new form ConsultaClienteView
     */
    public ConsultaClienteView() {
        this.clientesTable = new ArrayList<>();
        this.clientesMap = new TreeMap<>();
        this.clientes = ClienteBusiness.getClientes();
        initComponents();
        initListeners();
        mapearClientes(clientes);
        tableConsultaClienteResultado.setShowGrid(true);
        tableConsultaClienteResultado.setGridColor(Color.BLACK);
    }

    private void initListeners() {
        this.bConsultarCodigo.addActionListener(trataBotoes);
        this.bConsultarNome.addActionListener(trataBotoes);
        this.bConsultarCpf.addActionListener(trataBotoes);
        this.bConsultarCnpj.addActionListener(trataBotoes);
        this.bSortear.addActionListener(trataBotoes);

        this.bAlterar.addActionListener(trataBotoes);
        this.bVisualizar.addActionListener(trataBotoes);
        this.bBloquear.addActionListener(trataBotoes);
        this.bCancelar.addActionListener(trataBotoes);
        this.bReativar.addActionListener(trataBotoes);

        this.tCodigo.addKeyListener(trataTeclas);
        this.bConsultarCodigo.addKeyListener(trataTeclas);

        this.tNome.addKeyListener(trataTeclas);
        this.bConsultarNome.addKeyListener(trataTeclas);

        this.tMaximoContemplados.addKeyListener(trataTeclas);
        this.bSortear.addKeyListener(trataTeclas);

        this.rbCodigo.addActionListener(trataBotoes);
        this.rbNome.addActionListener(trataBotoes);
        this.rbCidade.addActionListener(trataBotoes);
    }

    private void mapearClientes(List<ClienteBean> clientes) {
        for (ClienteBean c : clientes) {
            clientesMap.put(c.getCodigoCliente(), c);
        }
    }

    private boolean consultarClientePorCodigo(int codigoCliente) {
        mapearClientes(clientes);
        boolean sucess = true;
        if (clientesTable != null) {
            clientesTable.clear();
        }
        if (!clientesMap.containsKey(codigoCliente)) {
            sucess = false;
        } else {
            cliente = clientesMap.get(codigoCliente);
            clientesTable.add(cliente);
        }
        return sucess;
    }

    private boolean consultaClientePorNome(String nome) {
        mapearClientes(clientes);
        boolean sucess = true;
        if (clientesTable != null) {
            clientesTable.clear();
        }
        for (Integer key : clientesMap.keySet()) {
            ClienteBean c = clientesMap.get(key);
            String nomeAux = c.getNome();
            if (nomeAux.toLowerCase().contains(nome.toLowerCase())) {
                clientesTable.add(c);
            }
        }
        return sucess;
    }

    private boolean consultaClientePorCpf(String cpf) {
        mapearClientes(clientes);
        boolean sucess = true;

        return sucess;
    }

    private boolean consultaClientePorCnpj(String cnpj) {
        mapearClientes(clientes);
        boolean sucess = true;

        return sucess;
    }

    private void mostra() {
        ClienteTableModel model = new ClienteTableModel();
        model.limpaLista();
        model.adicionaLista(clientesTable);
        for (int i = 0; i < clientesTable.size(); i++) {
            for (int j = 1; j < 5; j++) {
                model.isCellEditable(i, j);
            }
        }
        tableConsultaClienteResultado.setModel(model);
        TableColumn column = tableConsultaClienteResultado.getColumnModel().getColumn(3);
        JComboBox combo = new JComboBox(new DefaultComboBoxModel(UnidadeFederativa.values()));
        column.setCellEditor(new DefaultCellEditor(combo));
        column = tableConsultaClienteResultado.getColumnModel().getColumn(4);
        combo = new JComboBox(new DefaultComboBoxModel(EstadoCliente.values()));
        column.setCellEditor(new DefaultCellEditor(combo));
    }

    public void sortear() throws HeadlessException {
        mapearClientes(clientes);
        try {
            int maximoContemplados = Integer.valueOf(tMaximoContemplados.getText());
            List<ClienteBean> participantes = new ArrayList<>();
            if (rbFisico.isSelected()) {
                for (Integer key : clientesMap.keySet()) {
                    if (clientesMap.get(key) instanceof ClienteFisicoBean) {
                        participantes.add(clientesMap.get(key));
                    }
                }
            } else if (rbJuridico.isSelected()) {
                for (Integer key : clientesMap.keySet()) {
                    if (clientesMap.get(key) instanceof ClienteJuridicoBean) {
                        participantes.add(clientesMap.get(key));
                    }
                }
            } else {
                participantes.addAll(new ArrayList<>(clientesMap.values()));
            }
            if (maximoContemplados <= participantes.size()) {
                Sorteador sorteador = new Sorteador(participantes);
                sorteador.sortear(maximoContemplados);
                clientesTable = sorteador.getContemplados();
                ClienteTableModel model = new ClienteTableModel();
                model.limpaLista();
                model.adicionaLista(clientesTable);
                tableConsultaClienteResultado.setModel(model);
            } else {
                JOptionPane.showMessageDialog(null,
                        "Numero de conteos superior ao numero de clientes!",
                        "Erro",
                        JOptionPane.ERROR_MESSAGE);
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(null,
                    "Numero de contemplados invalido!",
                    "Erro",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        bgTipoPessoa = new javax.swing.ButtonGroup();
        bgTipoOrdenacao = new javax.swing.ButtonGroup();
        tbConsultaCliente = new javax.swing.JTabbedPane();
        pConsultarCodigo = new javax.swing.JPanel();
        tCodigo = new javax.swing.JTextField();
        bConsultarCodigo = new javax.swing.JButton();
        pConsultarNome = new javax.swing.JPanel();
        tNome = new javax.swing.JTextField();
        bConsultarNome = new javax.swing.JButton();
        pConsultarCpf = new javax.swing.JPanel();
        bConsultarCpf = new javax.swing.JButton();
        tCpf = new javax.swing.JFormattedTextField();
        pConsultarCnpj = new javax.swing.JPanel();
        tCnpj = new javax.swing.JFormattedTextField();
        bConsultarCnpj = new javax.swing.JButton();
        pSorteioClientes = new javax.swing.JPanel();
        tMaximoContemplados = new javax.swing.JTextField();
        bSortear = new javax.swing.JButton();
        rbFisico = new javax.swing.JRadioButton();
        rbJuridico = new javax.swing.JRadioButton();
        rbTodos = new javax.swing.JRadioButton();
        pOrdenarClientes = new javax.swing.JPanel();
        rbCodigo = new javax.swing.JRadioButton();
        rbNome = new javax.swing.JRadioButton();
        rbCidade = new javax.swing.JRadioButton();
        spConsultaClienteResultado = new javax.swing.JScrollPane();
        tableConsultaClienteResultado = new javax.swing.JTable();
        pButtons = new javax.swing.JPanel();
        bAlterar = new javax.swing.JButton();
        bVisualizar = new javax.swing.JButton();
        bBloquear = new javax.swing.JButton();
        bCancelar = new javax.swing.JButton();
        bReativar = new javax.swing.JButton();
        tMensagem = new javax.swing.JLabel();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Consultar clientes por:");
        setPreferredSize(new java.awt.Dimension(600, 500));
        getContentPane().setLayout(new java.awt.GridBagLayout());

        bConsultarCodigo.setText("Consultar");

        javax.swing.GroupLayout pConsultarCodigoLayout = new javax.swing.GroupLayout(pConsultarCodigo);
        pConsultarCodigo.setLayout(pConsultarCodigoLayout);
        pConsultarCodigoLayout.setHorizontalGroup(
            pConsultarCodigoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pConsultarCodigoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(tCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 203, Short.MAX_VALUE)
                .addComponent(bConsultarCodigo)
                .addContainerGap())
        );
        pConsultarCodigoLayout.setVerticalGroup(
            pConsultarCodigoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pConsultarCodigoLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(pConsultarCodigoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bConsultarCodigo))
                .addContainerGap())
        );

        tbConsultaCliente.addTab("Codigo", pConsultarCodigo);

        bConsultarNome.setText("Consultar");

        javax.swing.GroupLayout pConsultarNomeLayout = new javax.swing.GroupLayout(pConsultarNome);
        pConsultarNome.setLayout(pConsultarNomeLayout);
        pConsultarNomeLayout.setHorizontalGroup(
            pConsultarNomeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pConsultarNomeLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(tNome, javax.swing.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(bConsultarNome)
                .addContainerGap())
        );
        pConsultarNomeLayout.setVerticalGroup(
            pConsultarNomeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pConsultarNomeLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(pConsultarNomeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bConsultarNome))
                .addContainerGap())
        );

        tbConsultaCliente.addTab("Nome", pConsultarNome);

        bConsultarCpf.setText("Consultar");

        javax.swing.GroupLayout pConsultarCpfLayout = new javax.swing.GroupLayout(pConsultarCpf);
        pConsultarCpf.setLayout(pConsultarCpfLayout);
        pConsultarCpfLayout.setHorizontalGroup(
            pConsultarCpfLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pConsultarCpfLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(tCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 90, Short.MAX_VALUE)
                .addComponent(bConsultarCpf)
                .addContainerGap())
        );
        pConsultarCpfLayout.setVerticalGroup(
            pConsultarCpfLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pConsultarCpfLayout.createSequentialGroup()
                .addContainerGap(13, Short.MAX_VALUE)
                .addGroup(pConsultarCpfLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bConsultarCpf)
                    .addComponent(tCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        tbConsultaCliente.addTab("CPF", pConsultarCpf);

        bConsultarCnpj.setText("Consultar");

        javax.swing.GroupLayout pConsultarCnpjLayout = new javax.swing.GroupLayout(pConsultarCnpj);
        pConsultarCnpj.setLayout(pConsultarCnpjLayout);
        pConsultarCnpjLayout.setHorizontalGroup(
            pConsultarCnpjLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pConsultarCnpjLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(tCnpj, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 90, Short.MAX_VALUE)
                .addComponent(bConsultarCnpj)
                .addContainerGap())
        );
        pConsultarCnpjLayout.setVerticalGroup(
            pConsultarCnpjLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pConsultarCnpjLayout.createSequentialGroup()
                .addContainerGap(13, Short.MAX_VALUE)
                .addGroup(pConsultarCnpjLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bConsultarCnpj)
                    .addComponent(tCnpj, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        tbConsultaCliente.addTab("CNPJ", pConsultarCnpj);

        bSortear.setText("Sortear");

        bgTipoPessoa.add(rbFisico);
        rbFisico.setText("Fisico");

        bgTipoPessoa.add(rbJuridico);
        rbJuridico.setText("Juridico");

        bgTipoPessoa.add(rbTodos);
        rbTodos.setSelected(true);
        rbTodos.setText("Todos");

        javax.swing.GroupLayout pSorteioClientesLayout = new javax.swing.GroupLayout(pSorteioClientes);
        pSorteioClientes.setLayout(pSorteioClientesLayout);
        pSorteioClientesLayout.setHorizontalGroup(
            pSorteioClientesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pSorteioClientesLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(tMaximoContemplados, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(rbFisico)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(rbJuridico)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(rbTodos)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(bSortear)
                .addContainerGap())
        );
        pSorteioClientesLayout.setVerticalGroup(
            pSorteioClientesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pSorteioClientesLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(pSorteioClientesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tMaximoContemplados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bSortear)
                    .addComponent(rbFisico)
                    .addComponent(rbJuridico)
                    .addComponent(rbTodos))
                .addContainerGap())
        );

        tbConsultaCliente.addTab("Sorteio", pSorteioClientes);

        bgTipoOrdenacao.add(rbCodigo);
        rbCodigo.setText("Codigo");

        bgTipoOrdenacao.add(rbNome);
        rbNome.setText("Nome");

        bgTipoOrdenacao.add(rbCidade);
        rbCidade.setSelected(true);
        rbCidade.setText("Cidade");

        javax.swing.GroupLayout pOrdenarClientesLayout = new javax.swing.GroupLayout(pOrdenarClientes);
        pOrdenarClientes.setLayout(pOrdenarClientesLayout);
        pOrdenarClientesLayout.setHorizontalGroup(
            pOrdenarClientesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pOrdenarClientesLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(rbCodigo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(rbNome)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(rbCidade)
                .addContainerGap(226, Short.MAX_VALUE))
        );
        pOrdenarClientesLayout.setVerticalGroup(
            pOrdenarClientesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pOrdenarClientesLayout.createSequentialGroup()
                .addContainerGap(17, Short.MAX_VALUE)
                .addGroup(pOrdenarClientesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rbCodigo)
                    .addComponent(rbNome)
                    .addComponent(rbCidade))
                .addContainerGap())
        );

        tbConsultaCliente.addTab("Ordenar clientes", pOrdenarClientes);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weighty = 0.5;
        getContentPane().add(tbConsultaCliente, gridBagConstraints);

        tableConsultaClienteResultado.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tableConsultaClienteResultado.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        spConsultaClienteResultado.setViewportView(tableConsultaClienteResultado);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 5.0;
        gridBagConstraints.weighty = 5.0;
        getContentPane().add(spConsultaClienteResultado, gridBagConstraints);

        pButtons.setLayout(new java.awt.GridBagLayout());

        bAlterar.setText("Alterar");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        pButtons.add(bAlterar, gridBagConstraints);

        bVisualizar.setText("Visualizar");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        pButtons.add(bVisualizar, gridBagConstraints);

        bBloquear.setText("Bloquear");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        pButtons.add(bBloquear, gridBagConstraints);

        bCancelar.setText("Cancelar");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        pButtons.add(bCancelar, gridBagConstraints);

        bReativar.setText("Reativar");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 0;
        pButtons.add(bReativar, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        getContentPane().add(pButtons, gridBagConstraints);

        tMensagem.setText(" ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        getContentPane().add(tMensagem, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private class TrataBotoes implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (ae.getSource() == bConsultarCodigo) {
                int codigoCliente;
                try {
                    codigoCliente = Integer.valueOf(tCodigo.getText());
                    if (consultarClientePorCodigo(codigoCliente)) {
                        tMensagem.setText(clientesTable.size() + " cliente(s).");
                    } else {
                        tMensagem.setText("Nao foi possivel realizar a consulta.");
                    }
                    mostra();
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(null,
                            "Codigo invalido!",
                            "Erro",
                            JOptionPane.ERROR_MESSAGE);
                }
            } else if (ae.getSource() == bConsultarNome) {
                String nome = tNome.getText();
                if (consultaClientePorNome(nome)) {
                    tMensagem.setText(clientesTable.size() + " cliente(s).");
                } else {
                    tMensagem.setText("Nao foi possivel realizar a consulta.");
                }
                mostra();
            } else if (ae.getSource() == bConsultarCpf) {
                String cpf = tCpf.getText();
                if (consultaClientePorCpf(cpf)) {
                    tMensagem.setText(clientesTable.size() + " cliente(s).");
                } else {
                    tMensagem.setText("Nao foi possivel realizar a consulta.");
                }
            } else if (ae.getSource() == bConsultarCnpj) {
                String cnpj = tCnpj.getText();
                if (consultaClientePorCnpj(cnpj)) {
                    tMensagem.setText(clientesTable.size() + " cliente(s).");
                } else {
                    tMensagem.setText("Nao foi possivel realizar a consulta.");
                }
            } else if (ae.getSource() == bSortear) {
                sortear();
            } else if (ae.getSource() == bAlterar) {
                int row = tableConsultaClienteResultado.getSelectedRow();
                if (row == -1) {
                    tMensagem.setText("Nao ha registro selecionado!");
                } else {
                    int codigoCliente = (int) tableConsultaClienteResultado.getModel().getValueAt(row, 0);
                    if (clientesMap.containsKey(codigoCliente)) {
                        tMensagem.setText("Cliente " + codigoCliente + " selecionado!");
                    }
                }
            } else if (ae.getSource() == bVisualizar) {
                int row = tableConsultaClienteResultado.getSelectedRow();
                if (row == -1) {
                    tMensagem.setText("Nao ha registro selecionado!");
                } else {
                    int codigoCliente = (int) tableConsultaClienteResultado.getModel().getValueAt(row, 0);
                    if (clientesMap.containsKey(codigoCliente)) {
                        try {
                            tMensagem.setText("Cliente " + codigoCliente + " selecionado!");
                            cliente = clientesMap.get(codigoCliente);
                            ClienteFisicoController controller = new ClienteFisicoController(Permissao.CONSULTAR_CLIENTE);
                            controller.visualizar(new ClienteView(false), cliente, false);
                        } catch (AcessoNegadoException ex) {
                            JOptionPane.showMessageDialog(Ambiente.getInstance().getDesktopPane(),
                                    ex.toString(), "Erro", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                }
            } else if (ae.getSource() == rbCodigo) {
                TableModel model = tableConsultaClienteResultado.getModel();
                int rows = model.getRowCount();
                if (rows > 1) {
                    Collections.sort(clientesTable);
                    ClienteTableModel clienteTableModel = new ClienteTableModel(clientesTable);
                    tableConsultaClienteResultado.setModel(clienteTableModel);
                } else {
                    tMensagem.setText("Nao ha clientes na lista!");
                }
            } else if (ae.getSource() == rbNome) {
                TableModel model = tableConsultaClienteResultado.getModel();
                int rows = model.getRowCount();
                if (rows > 1) {
                    Collections.sort(clientesTable, ClienteBean.ClienteBeanNameComparator);
                    ClienteTableModel clienteTableModel = new ClienteTableModel(clientesTable);
                    tableConsultaClienteResultado.setModel(clienteTableModel);
                } else {
                    tMensagem.setText("Nao ha clientes na lista!");
                }
            } else if (ae.getSource() == rbCidade) {
                TableModel model = tableConsultaClienteResultado.getModel();
                int rows = model.getRowCount();
                if (rows > 1) {
                    Collections.sort(clientesTable, ClienteBean.ClienteBeanCityComparator);
                    ClienteTableModel clienteTableModel = new ClienteTableModel(clientesTable);
                    tableConsultaClienteResultado.setModel(clienteTableModel);
                } else {
                    tMensagem.setText("Nao ha clientes na lista!");
                }
            }
        }
    }

    private class TrataTeclas implements KeyListener {

        @Override
        public void keyTyped(KeyEvent ke) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void keyPressed(KeyEvent ke) {
            if (ke.getKeyCode() == KeyEvent.VK_TAB || ke.getKeyCode() == KeyEvent.VK_ENTER) {
                if (ke.getSource() == tCodigo) {
                    bConsultarCodigo.requestFocus();
                } else if (ke.getSource() == bConsultarCodigo && ke.getKeyCode() == KeyEvent.VK_ENTER) {
                    int codigoCliente;
                    try {
                        codigoCliente = Integer.valueOf(tCodigo.getText());
                        if (consultarClientePorCodigo(codigoCliente)) {
                            tMensagem.setText(clientesTable.size() + " cliente(s).");
                        } else {
                            tMensagem.setText("Nao foi possivel realizar a consulta.");
                        }
                        mostra();
                    } catch (NumberFormatException ex) {
                        JOptionPane.showMessageDialog(null,
                                "Codigo invalido!",
                                "Erro",
                                JOptionPane.ERROR_MESSAGE);
                    }
                } else if (ke.getSource() == tNome) {
                    bConsultarNome.requestFocus();
                } else if (ke.getSource() == bConsultarNome && ke.getKeyCode() == KeyEvent.VK_ENTER) {
                    String nome = tNome.getText();
                    if (consultaClientePorNome(nome)) {
                        tMensagem.setText(clientesTable.size() + " cliente(s).");
                    } else {
                        tMensagem.setText("Nao foi possivel realizar a consulta.");
                    }
                    mostra();
                } else if (ke.getSource() == tMaximoContemplados) {
                    bSortear.requestFocus();
                } else if (ke.getSource() == bSortear && ke.getKeyCode() == KeyEvent.VK_ENTER) {
                    sortear();
                }
            }
        }

        @Override
        public void keyReleased(KeyEvent ke) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bAlterar;
    private javax.swing.JButton bBloquear;
    private javax.swing.JButton bCancelar;
    private javax.swing.JButton bConsultarCnpj;
    private javax.swing.JButton bConsultarCodigo;
    private javax.swing.JButton bConsultarCpf;
    private javax.swing.JButton bConsultarNome;
    private javax.swing.JButton bReativar;
    private javax.swing.JButton bSortear;
    private javax.swing.JButton bVisualizar;
    private javax.swing.ButtonGroup bgTipoOrdenacao;
    private javax.swing.ButtonGroup bgTipoPessoa;
    private javax.swing.JPanel pButtons;
    private javax.swing.JPanel pConsultarCnpj;
    private javax.swing.JPanel pConsultarCodigo;
    private javax.swing.JPanel pConsultarCpf;
    private javax.swing.JPanel pConsultarNome;
    private javax.swing.JPanel pOrdenarClientes;
    private javax.swing.JPanel pSorteioClientes;
    private javax.swing.JRadioButton rbCidade;
    private javax.swing.JRadioButton rbCodigo;
    private javax.swing.JRadioButton rbFisico;
    private javax.swing.JRadioButton rbJuridico;
    private javax.swing.JRadioButton rbNome;
    private javax.swing.JRadioButton rbTodos;
    private javax.swing.JScrollPane spConsultaClienteResultado;
    private javax.swing.JFormattedTextField tCnpj;
    private javax.swing.JTextField tCodigo;
    private javax.swing.JFormattedTextField tCpf;
    private javax.swing.JTextField tMaximoContemplados;
    private javax.swing.JLabel tMensagem;
    private javax.swing.JTextField tNome;
    private javax.swing.JTable tableConsultaClienteResultado;
    private javax.swing.JTabbedPane tbConsultaCliente;
    // End of variables declaration//GEN-END:variables

    private final TrataBotoes trataBotoes = new TrataBotoes();
    private final TrataTeclas trataTeclas = new TrataTeclas();
}
